package com.csmk.springboot_simple.common;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageSerializable;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@SuppressWarnings({"rawtypes", "unchecked"})
public class PageRes<T> extends PageSerializable<T> {
    public static final int DEFAULT_NAVIGATE_PAGES = 8;
    /**
     * 当前页
     */
    private int pageNum;
    /**
     * 每页的数量
     */
    private int pageSize;


    public PageRes() {
    }

    /**
     * 包装Page对象
     *
     * @param list
     */
    public PageRes(List<? extends T> list) {
        this(list, DEFAULT_NAVIGATE_PAGES);
    }

    /**
     * 包装Page对象
     *
     * @param list          page结果
     * @param navigatePages 页码数量
     */
    public PageRes(List<? extends T> list, int navigatePages) {
        super(list);
        if (list instanceof Page) {
            Page page = (Page) list;
            this.pageNum = page.getPageNum();
            this.pageSize = page.getPageSize();

        } else if (list instanceof Collection) {
            this.pageNum = 1;
            this.pageSize = list.size();
        }
    }

    public static <T> PageRes<T> of(List<? extends T> list) {
        return new PageRes<T>(list);
    }


    /**
     * 手动指定总记录数获取分页信息
     *
     * @param total 总记录数
     * @param list  page结果
     */
    public static <T> PageRes<T> of(long total, List<? extends T> list) {
        if (list instanceof Page) {
            Page page = (Page) list;
            page.setTotal(total);
        }
        return new PageRes<T>(list);
    }

    public static <T> PageRes<T> of(List<? extends T> list, int navigatePages) {
        return new PageRes<T>(list, navigatePages);
    }



    /**
     * 数据对象转换
     *
     * @param function 用以转换数据对象的函数
     * @param <E>      目标类型
     * @return 转换了对象类型的包装结果
     */
    public <E> PageRes<E> convert(Page.Function<T, E> function) {
        List<E> list = new ArrayList<E>(this.list.size());
        for (T t : this.list) {
            list.add(function.apply(t));
        }
        PageRes<E> newPageInfo = new PageRes<>(list);
        newPageInfo.setPageNum(this.pageNum);
        newPageInfo.setPageSize(this.pageSize);
        newPageInfo.setTotal(this.total);
        return newPageInfo;
    }


    public int getPageNum() {
        return pageNum;
    }

    public void setPageNum(int pageNum) {
        this.pageNum = pageNum;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }


    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("PageInfo{");
        sb.append("pageNum=").append(pageNum);
        sb.append(", pageSize=").append(pageSize);
        sb.append(", total=").append(total);
        sb.append(", list=").append(list);
        sb.append(", navigatepageNums=");
        sb.append('}');
        return sb.toString();
    }
}
